package main

import (
	"fmt"
	"log"
	"time"

	"github.com/louloulin/dataflare/pkg/controller"
	"github.com/louloulin/dataflare/pkg/controller/client"
	"github.com/louloulin/dataflare/pkg/controller/metadata"
	"github.com/louloulin/dataflare/pkg/controller/resource"
)

func main() {
	// 创建控制器配置
	config := controller.DefaultControllerConfig()
	config.ClusterConfig.NodeID = "node-1"
	config.ClusterConfig.NodeName = "Node 1"
	config.ClusterConfig.BindAddr = "127.0.0.1:8000"

	// 创建控制器
	ctrl, err := controller.NewController(config)
	if err != nil {
		log.Fatalf("Failed to create controller: %v", err)
	}

	// 启动控制器
	log.Println("Starting controller...")
	err = ctrl.Start()
	if err != nil {
		log.Fatalf("Failed to start controller: %v", err)
	}
	defer ctrl.Stop()

	// 获取元数据管理器
	metadataManager := ctrl.GetMetadataManager()

	// 创建主题元数据
	log.Println("Creating topic metadata...")
	topicData := map[string]interface{}{
		"name":       "example-topic",
		"partitions": 3,
		"replicas":   2,
		"config": map[string]interface{}{
			"retention.ms":   86400000,
			"segment.bytes":  1073741824,
			"cleanup.policy": "delete",
		},
	}
	topic, err := metadataManager.Create(metadata.MetadataTypeTopic, "example-topic", topicData)
	if err != nil {
		log.Fatalf("Failed to create topic metadata: %v", err)
	}
	log.Printf("Created topic: %s (version: %d)", topic.ID, topic.Version)

	// 创建分区元数据
	for i := 0; i < 3; i++ {
		partitionID := fmt.Sprintf("example-topic-%d", i)
		partitionData := map[string]interface{}{
			"topic":     "example-topic",
			"id":        i,
			"leader":    "node-1",
			"replicas":  []string{"node-1", "node-2"},
			"isr":       []string{"node-1", "node-2"},
			"size":      0,
			"offset":    0,
			"timestamp": time.Now().Unix(),
		}
		partition, err := metadataManager.Create(metadata.MetadataTypePartition, partitionID, partitionData)
		if err != nil {
			log.Fatalf("Failed to create partition metadata: %v", err)
		}
		log.Printf("Created partition: %s (version: %d)", partition.ID, partition.Version)
	}

	// 获取资源管理器
	resourceManager := ctrl.GetResourceManager()

	// 注册节点资源
	log.Println("Registering node resources...")
	resourceManager.GetAllocator().RegisterNode("node-1")
	resourceManager.GetAllocator().RegisterNode("node-2")

	// 设置节点容量
	err = resourceManager.UpdateNodeCapacity("node-1", resource.ResourceTypeCPU, 8)
	if err != nil {
		log.Fatalf("Failed to update node-1 CPU capacity: %v", err)
	}
	err = resourceManager.UpdateNodeCapacity("node-1", resource.ResourceTypeMemory, 16384)
	if err != nil {
		log.Fatalf("Failed to update node-1 memory capacity: %v", err)
	}
	err = resourceManager.UpdateNodeCapacity("node-2", resource.ResourceTypeCPU, 4)
	if err != nil {
		log.Fatalf("Failed to update node-2 CPU capacity: %v", err)
	}
	err = resourceManager.UpdateNodeCapacity("node-2", resource.ResourceTypeMemory, 8192)
	if err != nil {
		log.Fatalf("Failed to update node-2 memory capacity: %v", err)
	}

	// 分配资源
	log.Println("Allocating resources...")
	requirements := []resource.ResourceRequirement{
		{Type: resource.ResourceTypeCPU, Quantity: 2},
		{Type: resource.ResourceTypeMemory, Quantity: 4096},
	}
	nodeID, err := resourceManager.AllocateTask(requirements)
	if err != nil {
		log.Fatalf("Failed to allocate task: %v", err)
	}
	log.Printf("Task allocated to node: %s", nodeID)

	// 获取客户端协调器
	clientCoordinator := ctrl.GetClientCoordinator()

	// 注册客户端
	log.Println("Registering clients...")
	client1, err := clientCoordinator.RegisterClient("client-1", "127.0.0.1:9001")
	if err != nil {
		log.Fatalf("Failed to register client-1: %v", err)
	}
	log.Printf("Registered client: %s (%s)", client1.ID, client1.Address)

	client2, err := clientCoordinator.RegisterClient("client-2", "127.0.0.1:9002")
	if err != nil {
		log.Fatalf("Failed to register client-2: %v", err)
	}
	log.Printf("Registered client: %s (%s)", client2.ID, client2.Address)

	// 更新客户端状态
	err = clientCoordinator.UpdateClientStatus("client-1", client.ClientStatusBusy)
	if err != nil {
		log.Fatalf("Failed to update client-1 status: %v", err)
	}
	log.Printf("Updated client-1 status to: %s", client.ClientStatusBusy.String())

	// 更新客户端元数据
	clientMetadata := map[string]string{
		"version": "1.0.0",
		"os":      "linux",
		"arch":    "amd64",
	}
	err = clientCoordinator.UpdateClientMetadata("client-2", clientMetadata)
	if err != nil {
		log.Fatalf("Failed to update client-2 metadata: %v", err)
	}
	log.Printf("Updated client-2 metadata: %v", clientMetadata)

	// 获取客户端路由器
	clientRouter := ctrl.GetClientRouter()

	// 创建客户端请求
	request := &client.ClientRequest{
		ClientID:    "client-1",
		RequestID:   "req-1",
		RequestType: "metadata.list",
		Data: map[string]interface{}{
			"type": string(metadata.MetadataTypeTopic),
		},
		Timestamp: time.Now(),
	}

	// 处理请求
	log.Println("Processing client request...")
	response := clientRouter.Route(request)
	if response.Success {
		log.Printf("Request succeeded: %s", request.RequestType)
	} else {
		log.Printf("Request failed: %s - %s", request.RequestType, response.Error)
	}

	// 打印系统状态
	log.Println("\nSystem Status:")
	topics, _ := metadataManager.List(metadata.MetadataTypeTopic)
	partitions, _ := metadataManager.List(metadata.MetadataTypePartition)
	log.Printf("Topics: %d", len(topics))
	log.Printf("Partitions: %d", len(partitions))
	log.Printf("Nodes: %d", len(resourceManager.GetAllNodeResources()))
	log.Printf("Clients: %d", len(clientCoordinator.GetAllClients()))
	log.Printf("Busy Clients: %d", len(clientCoordinator.GetBusyClients()))
	log.Printf("Idle Clients: %d", len(clientCoordinator.GetIdleClients()))

	log.Println("Controller example completed successfully")
}
